import { defineStore } from 'pinia'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { doLogin, getUserInfo } from '../api/auth'
import Cookies from 'js-cookie'

// 用户状态接口
interface UserState {
  id: string | null
  name: string | null
  email: string | null
  phone: string | null
  role: string | null
  token: string | null
  isLoggedIn: boolean
  avatar: string | null
  currentUser: any | null
}

// 登录参数接口
interface LoginParams {
  account: string
  password: string
  rememberMe?: boolean
}

// 注册参数接口
interface RegisterParams {
  phone: string
  password: string
  verificationCode: string
  accountName: string
  
}

// API基础URL
// const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '/api'

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: null,
    name: null,
    email: null,
    phone: null,
    role: null,
    token: null,
    isLoggedIn: false,
    avatar: null,
    currentUser: null
  }),
  
  getters: {
    getUserInfo: (state) => state,
    isAuthenticated: (state) => state.isLoggedIn && !!state.token,
    isSeller: (state) => state.role === 'seller',
    isBuyer: (state) => state.role === 'buyer',
    isBidder: (state) => state.role === 'bidder'
  },
  
  actions: {
    // 使用用户数据更新状态
    setUserData(userData: Partial<UserState>) {
      this.id = userData.id || this.id
      this.name = userData.name || this.name
      this.email = userData.email || this.email
      this.phone = userData.phone || this.phone
      this.role = userData.role || this.role
      this.token = userData.token || this.token
      this.avatar = userData.avatar || this.avatar
      this.isLoggedIn = true
      
      // 保存到本地存储
      localStorage.setItem('user', JSON.stringify({
        id: this.id,
        name: this.name,
        email: this.email,
        phone: this.phone,
        role: this.role,
        token: this.token,
        avatar: this.avatar
      }))
    },
    
    // 设置token
    setToken(token: string) {
      this.token = token;
      // 将token存储到cookie中
      Cookies.set('token', token);
    },

    // 设置当前用户信息
    setCurrentUser(user: any) {
      this.currentUser = user;
      // 更新基本用户信息
      if (user) {
        this.id = user.id || null;
        this.name = user.name || null;
        this.email = user.email || null;
        this.phone = user.phone || null;
        this.role = user.role || null;
        this.avatar = user.avatar || null;
        this.isLoggedIn = true;
      }
    },

    // 账号密码登录
    async login(params: LoginParams) {
      try {
        const response = await doLogin({
          account: params.account,
          password: params.password
        });

        if (response.code === 200 && response.data) {
          // 设置token
          this.setToken(response.data.e1);
          // 设置用户信息
          this.setCurrentUser(response.data.e2);
          
          // 如果选择记住我，设置更长的过期时间
          if (params.rememberMe) {
            Cookies.set('token', response.data.e1, { expires: 7 }); // 7天过期
          }
          //  const responseuser = await getUserInfo();
          //  console.log(responseuser,'responseuser');

          ElMessage.success('登录成功');
          return response.data;
        } else {
          throw new Error(response.message || '登录失败');
        }
      } catch (error: any) {
        console.error('Login failed:', error);
        ElMessage.error(error.message || '登录失败');
        throw error;
      }
    },
    
    // 注册新用户
    async register(params: RegisterParams) {
      try {
        console.log('Registering user:', params);
        // 实际项目中，这里应该调用后端API
        // const response = await axios.post(`${API_BASE_URL}/auth/register`, params)
        // const { data } = response
        
        // 模拟API响应
        const data = {
          success: true,
          message: 'Registration successful'
        }
        
        return data
      } catch (error: any) {
        console.error('Registration failed:', error)
        throw new Error(error.response?.data?.message || 'Registration failed')
      }
    },
    
    // 发送验证码
    async sendVerificationCode(phone: string) {
      try {
         console.log('Sending verification code to phone:', phone);
        // 实际项目中，这里应该调用后端API
        // const response = await axios.post(`${API_BASE_URL}/auth/send-code`, { phone })
        // const { data } = response
        
        // 模拟API响应
        const data = {
          success: true,
          message: 'Verification code sent'
        }
        
        return data
      } catch (error: any) {
        console.error('Failed to send verification code:', error)
        throw new Error(error.response?.data?.message || 'Failed to send verification code')
      }
    },
    
    // 检查是否已登录
    async checkLogin() {
      const token = Cookies.get('token');
      console.log('token:', token);
      if (token && !this.isLoggedIn) {
        try {
          // 设置token到axios headers
          axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
          // 调用获取用户信息的API
          const response = await getUserInfo();
          if (response.code === 200 && response.data) {
            this.setCurrentUser(response.data);
            this.setToken(token);
            return true;
          } else {
            throw new Error(response.message || '获取用户信息失败');
          }
        } catch (error) {
          console.error('Failed to get user info:', error);
          this.clearLoginState();
          return false;
        }
      }
      return this.isLoggedIn;
    },
    
    // 清除登录状态
    clearLoginState() {
      this.id = null;
      this.name = null;
      this.email = null;
      this.phone = null;
      this.role = null;
      this.token = null;
      this.avatar = null;
      this.isLoggedIn = false;
      this.currentUser = null;
      
      // 清除本地存储
      localStorage.removeItem('user');
      // 清除cookie
      Cookies.remove('token');
      // 清除axios headers
      delete axios.defaults.headers.common['Authorization'];
    },
    
    // 登出
    async logout() {
      try {
        // TODO: 这里可以添加退出登录的API调用
        // await logoutAPI();
        this.clearLoginState();
        ElMessage.success('退出登录成功');
      } catch (error) {
        console.error('Logout failed:', error);
        ElMessage.error('退出登录失败');
      }
    },
    
    // 从本地存储初始化
    initializeFromLocalStorage() {
      // 检查cookie中的token
      const token = Cookies.get('token');
      if (token) {
        // 设置token到axios headers
        axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        this.token = token;
        this.isLoggedIn = true;
      }
      
      // 检查localStorage中的用户信息
      const storedUser = localStorage.getItem('user');
      if (storedUser) {
        try {
          const userData = JSON.parse(storedUser);
          this.setUserData(userData);
        } catch (error) {
          console.error('Failed to parse user data from localStorage', error);
          this.clearLoginState();
        }
      }
    },
    
    // 更新用户信息
    async updateUserInfo(userData: Partial<UserState>) {
      try {
        // 实际项目中，这里应该调用后端API
        // const response = await axios.put(`${API_BASE_URL}/user/profile`, userData)
        // const { data } = response
        
        // 更新状态
        this.setUserData(userData)
        
        return { success: true }
      } catch (error: any) {
        console.error('Failed to update user info:', error)
        throw new Error(error.response?.data?.message || 'Failed to update user info')
      }
    }
  }
})